package com.bdqn.t296.noso.controller;

import com.alibaba.druid.sql.visitor.functions.Right;
import com.bdqn.t296.noso.entity.Menu;
import com.bdqn.t296.noso.entity.Role;
import com.bdqn.t296.noso.entity.User;
import com.bdqn.t296.noso.mapper.UserMapper;
import com.bdqn.t296.noso.service.MenuService;
import com.bdqn.t296.noso.service.RoleService;
import com.bdqn.t296.noso.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;

/**
 * 登录
 */
@Controller
public class LoginController {
    @Resource
    MenuService menuService;
    @Resource
    RoleService roleService;

    //配置欢迎页面
    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        return "login";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    @RequestMapping("/403")
    public String noauth() {
        return "403";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //清空session
        session.removeAttribute("sessionuser");
        return "login";
    }

    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }

    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "loginname") String loginname,
                          @RequestParam(value = "pwd") String pwd,
                          Model model,
                          HttpSession session) {
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(loginname, pwd);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
            //认证(登录)成功
            User user = (User) subject.getPrincipal();
            //获取权限
            Role role = roleService.userRole(user.getUserid()); //如果一对多关联不是立即加载，则需要通过用户获取角色
            user.setRole(role);
            List<Menu> menus = menuService.seleMenu(role);
            role.getMenus().addAll(menus);
            session.setAttribute("sessionuser", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

}
